package res

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	validate "muziai-server/utils/vaildate"
)

type Code int

const (
	SucessCode        Code = 0
	validataErrorCode Code = 7 //校验错误
)

type Response struct {
	Code Code   `json:"code"`
	Msg  string `json:"msg"`
	Data any    `json:"data"`
}

func response(c *gin.Context, code Code, data any, msg string) {
	responseObj := Response{Code: code, Data: data, Msg: msg}
	c.JSON(200, responseObj)
}

func Ok(c *gin.Context, data any, msg string) {
	response(c, SucessCode, data, msg)
}

func OkWithData(c *gin.Context, data any) {
	Ok(c, data, "成功")
}

func OkWithMsg(c *gin.Context, msg string) {
	Ok(c, map[string]any{}, msg)
}
func OkWithList(c *gin.Context, list any, count int64) {
	Ok(c, map[string]any{
		"count": count,
		"list":  list,
	}, "成功")
}

func Fail(c *gin.Context, code Code, data any, msg string) {
	response(c, code, data, msg)
}
func FailWithMsg(c *gin.Context, msg string) {
	Fail(c, validataErrorCode, map[string]any{}, msg)
}
func FailWithError(c *gin.Context, err error) {
	errMsg := validate.ValidateError(err)
	Fail(c, validataErrorCode, map[string]any{}, errMsg)

}
func FailWithCode(c *gin.Context, code Code) {
	Fail(c, code, map[string]any{}, "")
}

func SSE(c *gin.Context, code Code, data any, msg string) {
	responseObj := Response{Code: code, Data: data, Msg: msg}
	byteData, _ := json.Marshal(responseObj)
	c.SSEvent("", string(byteData))
	c.Writer.Flush()
}

func SSEOkWithData(c *gin.Context, data any) {

	SSE(c, SucessCode, data, "ok")
}
func SSEFailWithMsg(c *gin.Context, msg string) {
	SSE(c, validataErrorCode, nil, msg)
}
func SSEFailWithError(c *gin.Context, err error) {
	errMsg := validate.ValidateError(err)
	SSEFailWithMsg(c, errMsg)
}
